#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
MCP服务测试用例
从客户流失记录和ABC银行流失率数据中随机选择20个客户进行MCP服务测试
"""

import pandas as pd
import numpy as np
import random
import json
import sys
import os
from datetime import datetime
import warnings
warnings.filterwarnings('ignore')

def load_and_sample_data():
    """
    加载数据并随机采样20个客户
    """
    print("🔄 正在加载客户数据...")
    
    # 加载两个数据文件
    file1 = r"c:\Users\ten\Desktop\ad-space-available-master\ad-space-available-master\ad-space-available\project\客户流失记录.csv"
    file2 = r"c:\Users\ten\Desktop\ad-space-available-master\ad-space-available-master\ad-space-available\project\ABC Multistate 银行流失率.csv"
    
    try:
        # 读取客户流失记录
        df1 = pd.read_csv(file1, encoding='utf-8')
        print(f"✅ 客户流失记录数据加载成功，共{len(df1)}条记录")
        
        # 读取ABC银行流失率数据
        df2 = pd.read_csv(file2, encoding='utf-8')
        print(f"✅ ABC银行流失率数据加载成功，共{len(df2)}条记录")
        
        # 统一列名映射
        column_mapping = {
            '客户ID': 'customer_id',
            '信用评分': 'credit_score', 
            '信用分': 'credit_score',
            '地理位置': 'country',
            '国家': 'country',
            '性别': 'gender',
            '年龄': 'age',
            '任期': 'tenure',
            '余额': 'balance',
            '产品数量': 'products_number',
            '银行产品编号': 'products_number',
            '拥有收藏卡判定': 'has_credit_card',
            '信用卡': 'has_credit_card',
            '活跃成员判定': 'is_active_member',
            '活跃成员': 'is_active_member',
            '评估薪资': 'estimated_salary',
            '估计薪水': 'estimated_salary',
            '退出': 'exited',
            '流失率': 'exited'
        }
        
        # 重命名列
        df1_renamed = df1.rename(columns=column_mapping)
        df2_renamed = df2.rename(columns=column_mapping)
        
        # 确保必要的列存在
        required_cols = ['customer_id', 'credit_score', 'country', 'gender', 'age', 
                        'tenure', 'balance', 'products_number', 'has_credit_card', 
                        'is_active_member', 'estimated_salary']
        
        # 从两个数据集中各选择10个客户
        sample1 = df1_renamed[required_cols].sample(n=10, random_state=42)
        sample2 = df2_renamed[required_cols].sample(n=10, random_state=42)
        
        # 合并样本
        test_sample = pd.concat([sample1, sample2], ignore_index=True)
        
        print(f"✅ 成功生成测试样本，共{len(test_sample)}个客户")
        return test_sample
        
    except Exception as e:
        print(f"❌ 数据加载失败: {e}")
        return None

def prepare_mcp_test_data(sample_df):
    """
    准备MCP服务测试数据
    """
    print("🔄 准备MCP服务测试数据...")
    
    test_customers = []
    
    for _, row in sample_df.iterrows():
        customer_data = {
            "customer_id": str(row['customer_id']),
            "credit_score": float(row['credit_score']),
            "country": str(row['country']),
            "gender": str(row['gender']),
            "age": int(row['age']),
            "tenure": int(row['tenure']),
            "balance": float(row['balance']),
            "products_number": int(row['products_number']),
            "has_credit_card": int(row['has_credit_card']),
            "is_active_member": int(row['is_active_member']),
            "estimated_salary": float(row['estimated_salary'])
        }
        test_customers.append(customer_data)
    
    print(f"✅ MCP测试数据准备完成，共{len(test_customers)}个客户")
    return test_customers

def save_test_data(test_customers):
    """
    保存测试数据到JSON文件
    """
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    filename = f'mcp_测试数据_{timestamp}.json'
    
    with open(filename, 'w', encoding='utf-8') as f:
        json.dump({
            "test_info": {
                "timestamp": timestamp,
                "total_customers": len(test_customers),
                "description": "MCP服务测试用例数据"
            },
            "customers": test_customers
        }, f, ensure_ascii=False, indent=2)
    
    print(f"💾 测试数据已保存到: {filename}")
    return filename

def display_sample_data(test_customers, num_display=5):
    """
    显示部分样本数据
    """
    print(f"\n📋 显示前{num_display}个客户的测试数据:")
    print("=" * 80)
    
    for i, customer in enumerate(test_customers[:num_display]):
        print(f"\n客户 {i+1}: {customer['customer_id']}")
        print(f"  信用分: {customer['credit_score']}")
        print(f"  国家: {customer['country']}")
        print(f"  性别: {customer['gender']}")
        print(f"  年龄: {customer['age']}岁")
        print(f"  任期: {customer['tenure']}年")
        print(f"  余额: ¥{customer['balance']:,.2f}")
        print(f"  产品数量: {customer['products_number']}个")
        print(f"  信用卡: {'是' if customer['has_credit_card'] == 1 else '否'}")
        print(f"  活跃成员: {'是' if customer['is_active_member'] == 1 else '否'}")
        print(f"  估计薪水: ¥{customer['estimated_salary']:,.2f}")
        print("-" * 50)

def generate_mcp_test_instructions(test_customers):
    """
    生成MCP服务测试说明
    """
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    filename = f'mcp_测试说明_{timestamp}.md'
    
    instructions = f"""# MCP服务测试说明

## 测试概述
- 生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
- 测试客户数量: {len(test_customers)}个
- 数据来源: 客户流失记录.csv + ABC Multistate 银行流失率.csv

## 测试步骤

### 1. 单客户分析测试
使用MCP服务的 `comprehensive_customer_analysis` 工具对每个客户进行分析:

```python
# 示例调用
customer_data = {{
    "customer_id": "{test_customers[0]['customer_id']}",
    "credit_score": {test_customers[0]['credit_score']},
    "country": "{test_customers[0]['country']}",
    "gender": "{test_customers[0]['gender']}",
    "age": {test_customers[0]['age']},
    "tenure": {test_customers[0]['tenure']},
    "balance": {test_customers[0]['balance']},
    "products_number": {test_customers[0]['products_number']},
    "has_credit_card": {test_customers[0]['has_credit_card']},
    "is_active_member": {test_customers[0]['is_active_member']},
    "estimated_salary": {test_customers[0]['estimated_salary']}
}}
```

### 2. 批量分析测试
使用MCP服务的 `batch_customer_analysis` 工具进行批量分析:

```python
# 批量分析所有客户
batch_data = {{
    "customers": test_customers
}}
```

### 3. 模型性能查看
使用MCP服务的 `get_analysis_summary` 工具查看模型性能:

```python
# 获取分析摘要
# 无需参数
```

## 预期结果

每个客户分析应包含:
- 基本信息展示
- 流失概率预测
- 客户价值评估
- 风险等级分类
- 个性化干预策略
- 属性改善建议

## 测试验证点

1. **数据完整性**: 所有客户数据字段都被正确处理
2. **预测准确性**: 流失概率在0-100%范围内
3. **策略合理性**: 干预策略与客户风险等级匹配
4. **性能表现**: 批量处理能力和响应时间
5. **错误处理**: 异常数据的处理能力

## 测试数据统计

"""
    
    # 添加数据统计信息
    countries = [c['country'] for c in test_customers]
    genders = [c['gender'] for c in test_customers]
    ages = [c['age'] for c in test_customers]
    balances = [c['balance'] for c in test_customers]
    
    instructions += f"""- 国家分布: {dict(pd.Series(countries).value_counts())}
- 性别分布: {dict(pd.Series(genders).value_counts())}
- 年龄范围: {min(ages)}-{max(ages)}岁 (平均: {np.mean(ages):.1f}岁)
- 余额范围: ¥{min(balances):,.2f} - ¥{max(balances):,.2f}
- 零余额客户: {sum(1 for b in balances if b == 0)}个

## 注意事项

1. 确保MCP服务正常运行
2. 测试过程中记录响应时间
3. 验证输出格式的一致性
4. 检查特殊情况的处理(如零余额客户)
5. 对比批量分析和单客户分析的结果一致性
"""
    
    with open(filename, 'w', encoding='utf-8') as f:
        f.write(instructions)
    
    print(f"📝 测试说明已生成: {filename}")
    return filename

def main():
    """
    主函数
    """
    print("🚀 开始生成MCP服务测试用例...")
    print("=" * 60)
    
    # 1. 加载和采样数据
    sample_data = load_and_sample_data()
    if sample_data is None:
        print("❌ 数据加载失败，程序退出")
        return
    
    # 2. 准备MCP测试数据
    test_customers = prepare_mcp_test_data(sample_data)
    
    # 3. 显示样本数据
    display_sample_data(test_customers)
    
    # 4. 保存测试数据
    data_file = save_test_data(test_customers)
    
    # 5. 生成测试说明
    instruction_file = generate_mcp_test_instructions(test_customers)
    
    print(f"\n🎉 MCP服务测试用例生成完成！")
    print(f"📊 测试数据文件: {data_file}")
    print(f"📝 测试说明文件: {instruction_file}")
    print(f"\n📋 快速摘要:")
    print(f"   测试客户数量: {len(test_customers)}")
    print(f"   数据来源: 客户流失记录.csv + ABC银行流失率.csv")
    print(f"   可用于测试: 单客户分析、批量分析、模型性能查看")
    
    # 6. 提供下一步操作建议
    print(f"\n💡 下一步操作建议:")
    print(f"   1. 确保MCP服务正在运行")
    print(f"   2. 使用生成的测试数据调用MCP服务")
    print(f"   3. 验证分析结果的准确性和完整性")
    print(f"   4. 记录测试结果和性能指标")

if __name__ == "__main__":
    main()